package com.Xht.www.servlet;

//后端响应商家处理用户退款的请求

import com.Xht.www.dao.RoomTypeInfoDAO;
import com.Xht.www.dao.UserHistoryOrdersDAO;
import com.Xht.www.dao.UserWalletBalanceDAO;
import com.Xht.www.po.RoomTypeInfoPO;
import com.Xht.www.po.UserHistoryOrdersPO;
import com.Xht.www.po.UserWalletBalancePO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.List;

@WebServlet("/processRefund")
public class ProcessRefundServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            response.setContentType("application/json;charset=UTF-8");
            String action = request.getParameter("action");
            String merchantName = request.getParameter("merchantName");

            if ("list".equals(action)) {
                UserHistoryOrdersDAO dao = new UserHistoryOrdersDAO();
                List<UserHistoryOrdersPO> orders = dao.getAllOrdersByMerchantNameAndStatus(merchantName, "退款中");

                StringBuilder json = new StringBuilder("[");
                for (int i = 0; i < orders.size(); i++) {
                    UserHistoryOrdersPO order = orders.get(i);
                    json.append("{")
                            .append("\"orderId\":").append(order.getOrderId()).append(",")
                            .append("\"userId\":").append(order.getUserId()).append(",")
                            .append("\"merchantName\":\"").append(order.getMerchantName()).append("\",")
                            .append("\"roomTypeName\":\"").append(order.getRoomTypeName()).append("\",")
                            .append("\"bedType\":\"").append(order.getBedType()).append("\",")
                            .append("\"roomTypeQuantity\":").append(order.getRoomTypeQuantity()).append(",")
                            .append("\"checkInTime\":\"").append(order.getCheckInTime()).append("\",")
                            .append("\"checkOutTime\":\"").append(order.getCheckOutTime()).append("\",")
                            .append("\"totalConsumption\":\"").append(order.getTotalConsumption()).append("\"")
                            .append("}");
                    if (i < orders.size() - 1) {
                        json.append(",");
                    }
                }
                json.append("]");

                response.getWriter().write(json.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("[]");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 添加日志输出，确认请求到达
            System.out.println("Received POST request to ProcessRefundServlet");

            // 打印所有请求参数名，用于调试
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                System.out.println("Parameter: " + paramName + " = " + request.getParameter(paramName));
            }

            // 获取并验证orderId参数
            String orderIdParam = request.getParameter("orderId");
            if (orderIdParam == null || orderIdParam.trim().isEmpty()) {
                response.getWriter().write("错误：缺少订单ID参数");
                return;
            }

            // 安全地将字符串转换为整数
            int orderId;
            try {
                orderId = Integer.parseInt(orderIdParam);
            } catch (NumberFormatException e) {
                response.getWriter().write("错误：订单ID格式不正确");
                return;
            }

            // 获取并验证action参数
            String action = request.getParameter("action");
            if (action == null || !(action.equals("approve") || action.equals("reject"))) {
                response.getWriter().write("错误：无效的操作类型");
                return;
            }

            UserHistoryOrdersDAO orderDAO = new UserHistoryOrdersDAO();
            UserWalletBalanceDAO walletDAO = new UserWalletBalanceDAO();
            RoomTypeInfoDAO roomTypeDAO = new RoomTypeInfoDAO(); // 新增RoomTypeInfoDAO实例

            // 获取订单信息
            UserHistoryOrdersPO order = orderDAO.getOrderById(orderId);
            if (order == null) {
                response.getWriter().write("错误：找不到对应的订单");
                return;
            }

            // 获取订单金额
            String totalConsumptionStr = order.getTotalConsumption().toString();

            if (totalConsumptionStr == null || totalConsumptionStr.trim().isEmpty()) {
                response.getWriter().write("错误：订单金额信息缺失");
                return;
            }

            BigDecimal refundAmount;
            try {
                refundAmount = new BigDecimal(totalConsumptionStr);
            } catch (NumberFormatException e) {
                response.getWriter().write("错误：订单金额格式不正确");
                return;
            }

            if ("approve".equals(action)) {
                // 开始事务处理
                try {
                    // 更新订单状态为已退款
                    boolean orderSuccess = orderDAO.updateOrderStatusAndRemark(orderId, "已退款", "商家已同意退款申请");
                    if (!orderSuccess) {
                        throw new Exception("更新订单状态失败");
                    }

                    // 获取用户钱包信息
                    Integer userId = order.getUserId();
                    if (userId == null) {
                        throw new Exception("订单用户ID缺失");
                    }

                    UserWalletBalancePO wallet = walletDAO.getUserByUserId(userId);
                    if (wallet == null) {
                        // 用户钱包不存在，创建新钱包
                        wallet = new UserWalletBalancePO();
                        wallet.setUserId(userId);
                        wallet.setWalletId(walletDAO.getNextWalletId()); // 假设存在获取下一个钱包ID的方法
                        wallet.setTotalAmount(refundAmount);
                        wallet.setConsumptionAmount(BigDecimal.ZERO.subtract(refundAmount));
                        wallet.setRechargeAmount(BigDecimal.ZERO);
                        wallet.setTopUpAmount(BigDecimal.ZERO);
                        wallet.setRechargeAuditStatus("无");
                        wallet.setRechargeReason("退款");

                        boolean createSuccess = walletDAO.insertUserWalletBalance(wallet);
                        if (!createSuccess) {
                            throw new Exception("创建用户钱包失败");
                        }
                    } else {
                        // 更新用户钱包信息
                        BigDecimal newTotalAmount = wallet.getTotalAmount().add(refundAmount);
                        BigDecimal newConsumptionAmount = wallet.getConsumptionAmount().subtract(refundAmount);

                        wallet.setTotalAmount(newTotalAmount);
                        wallet.setConsumptionAmount(newConsumptionAmount);

                        boolean walletSuccess = walletDAO.updateUserWalletBalance(wallet);
                        if (!walletSuccess) {
                            throw new Exception("更新用户钱包失败");
                        }
                    }

                    // 更新房间信息：剩余数量+1，销量-1
                    RoomTypeInfoPO roomType = roomTypeDAO.queryRoomTypeInfoByMerchantNameAndBedType(
                            order.getMerchantName(), order.getBedType());

                    if (roomType == null) {
                        throw new Exception("找不到对应的房间类型信息");
                    }

                    // 更新房间数量和销量
                    int newRemainingQuantity = roomType.getRemainingQuantity() + 1;
                    int newSalesVolume = roomType.getSalesVolume() - 1;

                    roomType.setRemainingQuantity(newRemainingQuantity);
                    roomType.setSalesVolume(newSalesVolume);

                    boolean roomUpdateSuccess = roomTypeDAO.updateRoomTypeInfo(roomType);
                    if (!roomUpdateSuccess) {
                        throw new Exception("更新房间信息失败");
                    }

                    response.getWriter().write("退款已处理，钱包余额已更新，房间信息已调整");
                } catch (Exception e) {
                    // 事务回滚逻辑（需要数据库支持）
                    e.printStackTrace();
                    response.getWriter().write("处理退款时出错: " + e.getMessage());
                }
            } else if ("reject".equals(action)) {
                boolean success = orderDAO.updateOrderStatusAndRemark(orderId, "正常", "商家拒绝了你的退款申请");
                response.getWriter().write(success ? "已拒绝退款申请" : "处理拒绝请求失败");
            } else {
                response.getWriter().write("无效操作");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("处理请求时出错: " + e.getMessage());
        }
    }
}
